package proxy

import (
	"bufio"
	"bytes"
	"crypto/tls"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"strings"
	"time"

	"golang.org/x/net/http2"

	"network-firewall-go/internal/types"
	"network-firewall-go/internal/utils"
)

// performMITMInterceptionTCP 执行TCP版本的MITM拦截 - 实际被调用的版本
func (s *Server) performMITMInterceptionTCP(clientConn net.Conn, host string) error {
	// 生成证书
	cert, err := s.certManager.GetCertificate(host)
	if err != nil {
		return fmt.Errorf("获取证书失败: %w", err)
	}

	fmt.Printf("🔐 证书已准备: %s\n", host)

	// 创建TLS配置，同时支持HTTP/1.1和HTTP/2
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{*cert},
		NextProtos:   []string{"h2", "http/1.1"}, // 优先使用HTTP/2
	}

	// 包装为TLS连接
	tlsConn := tls.Server(clientConn, tlsConfig)

	// 执行TLS握手
	if err := tlsConn.Handshake(); err != nil {
		return fmt.Errorf("TLS握手失败: %w", err)
	}

	fmt.Printf("✅ TLS握手成功: %s\n", host)

	// 检查协商的协议
	state := tlsConn.ConnectionState()
	protocol := state.NegotiatedProtocol

	fmt.Printf("🔍 协商的协议: %s\n", protocol)

	switch protocol {
	case "h2":
		// 使用HTTP/2处理
		return s.handleHTTP2Connection(tlsConn, host)
	default:
		// 使用HTTP/1.1处理
		return s.handleDecryptedHTTPSTCP(tlsConn, host)
	}
}

// handleHTTP2Connection 处理HTTP/2连接
func (s *Server) handleHTTP2Connection(tlsConn *tls.Conn, host string) error {
	fmt.Printf("🔍 使用HTTP/2处理连接: %s\n", host)

	// 创建HTTP/2服务器
	server := &http2.Server{}

	// 创建HTTP处理器
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		s.handleHTTP2Request(w, r, host)
	})

	// 处理HTTP/2连接
	server.ServeConn(tlsConn, &http2.ServeConnOpts{
		Handler: handler,
	})

	return nil
}

// handleHTTP2Request 处理HTTP/2请求
func (s *Server) handleHTTP2Request(w http.ResponseWriter, r *http.Request, host string) {
	isDebugURL := strings.Contains(r.URL.Host, "app.y-i-y.com") && strings.Contains(r.URL.Path, "dewatermark")

	if isDebugURL {
		fmt.Printf("🔍 ========== HTTP/2请求RAW数据 ==========\n")
		fmt.Printf("🔍 Method: %s\n", r.Method)
		fmt.Printf("🔍 URL: %s\n", r.URL.String())
		fmt.Printf("🔍 Proto: %s\n", r.Proto)
		fmt.Printf("🔍 ProtoMajor: %d\n", r.ProtoMajor)
		fmt.Printf("🔍 ProtoMinor: %d\n", r.ProtoMinor)
		fmt.Printf("🔍 Host: %s\n", r.Host)
		fmt.Printf("🔍 Headers (%d total):\n", len(r.Header))
		for key, values := range r.Header {
			for _, value := range values {
				fmt.Printf("🔍   %s: %s\n", key, value)
			}
		}
		fmt.Printf("🔍 ============================================\n")
	}

	// 转发HTTP/2请求到后端
	resp, respBody, err := s.forwardHTTP2Request(r, isDebugURL)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}

	// 复制响应头
	for key, values := range resp.Header {
		for _, value := range values {
			w.Header().Add(key, value)
		}
	}

	// 设置状态码
	w.WriteHeader(resp.StatusCode)

	// 写入响应体
	if respBody != nil {
		w.Write(respBody)
	}

	// 记录事务
	s.recordHTTP2Transaction(r, resp, respBody, isDebugURL)
}

// forwardHTTP2Request 转发HTTP/2请求到后端
func (s *Server) forwardHTTP2Request(r *http.Request, isDebugURL bool) (*http.Response, []byte, error) {
	// 创建HTTP/2客户端
	transport := &http2.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true, // 在生产环境中应该验证证书
		},
	}

	client := &http.Client{
		Transport: transport,
		Timeout:   30 * time.Second,
	}

	// 创建新请求
	newReq, err := http.NewRequest(r.Method, r.URL.String(), r.Body)
	if err != nil {
		return nil, nil, fmt.Errorf("创建请求失败: %w", err)
	}

	// 完全复制所有请求头，包括HTTP/2特有的头部
	for key, values := range r.Header {
		for _, value := range values {
			newReq.Header.Add(key, value)
		}
	}

	if isDebugURL {
		fmt.Printf("🔍 转发HTTP/2请求头 (%d total):\n", len(newReq.Header))
		for key, values := range newReq.Header {
			for _, value := range values {
				fmt.Printf("🔍   %s: %s\n", key, value)
			}
		}
	}

	// 发送请求
	resp, err := client.Do(newReq)
	if err != nil {
		return nil, nil, fmt.Errorf("发送HTTP/2请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, nil, fmt.Errorf("读取HTTP/2响应失败: %w", err)
	}

	if isDebugURL {
		fmt.Printf("🔍 ========== HTTP/2响应RAW数据 ==========\n")
		fmt.Printf("🔍 Status: %s\n", resp.Status)
		fmt.Printf("🔍 StatusCode: %d\n", resp.StatusCode)
		fmt.Printf("🔍 Proto: %s\n", resp.Proto)
		fmt.Printf("🔍 Headers (%d total):\n", len(resp.Header))
		for key, values := range resp.Header {
			for _, value := range values {
				fmt.Printf("🔍   %s: %s\n", key, value)
			}
		}
		fmt.Printf("🔍 ============================================\n")
	}

	return resp, respBody, nil
}

// recordHTTP2Transaction 记录HTTP/2事务
func (s *Server) recordHTTP2Transaction(r *http.Request, resp *http.Response, respBody []byte, isDebugURL bool) {
	// 创建请求对象
	httpReq := types.NewHTTPRequest(
		r.Method,
		r.URL.String(),
		r.Proto,
		r.Header,
		nil, // body
		"",  // 客户端IP
		getTLSVersionFromRequest(r),
	)

	// 创建响应对象
	httpResp := types.NewHTTPResponse(
		resp.StatusCode,
		resp.Status,
		resp.Proto,
		resp.Header,
		respBody,
		getTLSVersionFromResponse(resp),
	)

	// 创建事务
	transaction := &types.HTTPTransaction{
		ID:        utils.GenerateID(),
		Request:   httpReq,
		Response:  httpResp,
		Timestamp: time.Now(),
		Duration:  0, // 这里可以计算实际耗时
	}

	// 保存到数据库
	if s.dbManager != nil {
		if err := s.dbManager.SaveTransaction(transaction); err != nil {
			log.Printf("保存HTTP/2事务失败: %v", err)
		}
	}

	// 发送WebSocket通知
	if s.wsServer != nil {
		s.wsServer.BroadcastTransaction(transaction)
	}

	if isDebugURL {
		fmt.Printf("🔍 ========== HTTP/2事务记录完成 ==========\n")
		fmt.Printf("🔍 Transaction.ID: %s\n", transaction.ID)
		fmt.Printf("🔍 Transaction.Request.Method: %s\n", transaction.Request.Method)
		fmt.Printf("🔍 Transaction.Request.URL: %s\n", transaction.Request.URL)
		fmt.Printf("🔍 Transaction.Request.HTTPVersion: %s\n", transaction.Request.HTTPVersion)
		fmt.Printf("🔍 Transaction.Response.StatusCode: %d\n", transaction.Response.StatusCode)
		fmt.Printf("🔍 Transaction.Response.HTTPVersion: %s\n", transaction.Response.HTTPVersion)
		fmt.Printf("🔍 ============================================\n")
	}
}

// 辅助函数
func getTLSVersionFromRequest(r *http.Request) string {
	if r.TLS != nil {
		return getTLSVersion(r.TLS.Version)
	}
	return ""
}

func getTLSVersionFromResponse(resp *http.Response) string {
	if resp.TLS != nil {
		return getTLSVersion(resp.TLS.Version)
	}
	return ""
}

// handleDecryptedHTTPSTCP 处理解密后的HTTPS流量（TCP版本）
func (s *Server) handleDecryptedHTTPSTCP(tlsConn *tls.Conn, host string) {
	for {
		// 设置读取超时（减少到30秒，便于快速停止）
		tlsConn.SetReadDeadline(time.Now().Add(30 * time.Second))

		// 读取HTTP请求
		reader := bufio.NewReader(tlsConn)
		req, err := http.ReadRequest(reader)
		if err != nil {
			if err == io.EOF {
				fmt.Printf("🔚 连接关闭: %s\n", host)
				return
			}
			// 对于超时错误，不打印日志以减少噪音
			if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
				fmt.Printf("⏰ 连接超时: %s\n", host)
				return
			}
			// 检查是否是连接被强制关闭的错误（常见且正常）
			errStr := err.Error()
			if strings.Contains(errStr, "wsarecv") ||
				strings.Contains(errStr, "connection was aborted") ||
				strings.Contains(errStr, "connection reset by peer") {
				fmt.Printf("📡 HTTPS连接被客户端中断: %s\n", host)
			} else {
				fmt.Printf("❌ 读取HTTPS请求失败: %v\n", err)
			}
			return
		}

		// 修复请求URL
		if req.URL.Scheme == "" {
			req.URL.Scheme = "https"
		}
		if req.URL.Host == "" {
			req.URL.Host = host
		}

		fmt.Printf("🔍 拦截到HTTPS请求: %s %s\n", req.Method, req.URL.String())

		// 处理HTTPS请求
		s.processHTTPSRequestTCP(tlsConn, req, host)
	}
}

// processHTTPSRequestTCP 处理HTTPS请求（TCP版本）
func (s *Server) processHTTPSRequestTCP(tlsConn *tls.Conn, req *http.Request, host string) {
	startTime := time.Now()
	requestID := utils.GenerateRequestID()

	// 🔍 只有当URL包含特定路径时才输出详细调试信息
	if strings.Contains(req.URL.Host, "app.y-i-y.com") && strings.Contains(req.URL.Path, "dewatermark") {
		fmt.Printf("🔍 ========== 原始HTTPS请求RAW数据 ==========\n")
		fmt.Printf("🔍 Method: %s\n", req.Method)
		fmt.Printf("🔍 URL: %s\n", req.URL.String())
		fmt.Printf("🔍 Proto: %s\n", req.Proto)
		fmt.Printf("🔍 ProtoMajor: %d\n", req.ProtoMajor)
		fmt.Printf("🔍 ProtoMinor: %d\n", req.ProtoMinor)
		fmt.Printf("🔍 Host: %s\n", req.Host)
		fmt.Printf("🔍 RemoteAddr: %s\n", req.RemoteAddr)
		fmt.Printf("🔍 RequestURI: %s\n", req.RequestURI)
		fmt.Printf("🔍 TLS: %v\n", req.TLS != nil)
		if req.TLS != nil {
			fmt.Printf("🔍 TLS Version: %d\n", req.TLS.Version)
		}
		fmt.Printf("🔍 ClientConn TLS Version: %d\n", tlsConn.ConnectionState().Version)
		fmt.Printf("🔍 Headers (%d total):\n", len(req.Header))
		for key, values := range req.Header {
			for _, value := range values {
				fmt.Printf("🔍   %s: %s\n", key, value)
			}
		}
		fmt.Printf("🔍 ============================================\n")
	}

	// 读取请求体
	var reqBody []byte
	if req.Body != nil {
		var err error
		reqBody, err = io.ReadAll(req.Body)
		if err != nil {
			fmt.Printf("❌ 读取请求体失败: %v\n", err)
			s.sendHTTPSErrorResponseTCP(tlsConn, 400, "Bad Request")
			return
		}
		req.Body.Close()

		// 重新设置请求体
		req.Body = io.NopCloser(bytes.NewReader(reqBody))
		if req.ContentLength == -1 {
			req.ContentLength = int64(len(reqBody))
		}
	}

	// 创建HTTP请求记录
	httpReq := types.NewHTTPRequest(req)
	httpReq.ID = requestID
	httpReq.Body = string(reqBody)
	httpReq.BodySize = int64(len(reqBody))
	httpReq.TLSVersion = s.getTLSVersion(tlsConn)

	// 🔍 只有当URL包含特定路径时才输出转换后的请求对象
	if strings.Contains(req.URL.Host, "app.y-i-y.com") && strings.Contains(req.URL.Path, "dewatermark") {
		fmt.Printf("🔍 ========== 转换后的HTTPS请求对象 ==========\n")
		fmt.Printf("🔍 HTTPRequest.HTTPVersion: %s\n", httpReq.HTTPVersion)
		fmt.Printf("🔍 HTTPRequest.Method: %s\n", httpReq.Method)
		fmt.Printf("🔍 HTTPRequest.URL: %s\n", httpReq.URL)
		fmt.Printf("🔍 HTTPRequest.Host: %s\n", httpReq.Host)
		fmt.Printf("🔍 HTTPRequest.TLSVersion: %s\n", httpReq.TLSVersion)
		fmt.Printf("🔍 HTTPRequest.Headers (转换后):\n")
		for key, value := range httpReq.Headers {
			fmt.Printf("🔍   %s: %s\n", key, value)
		}
		fmt.Printf("🔍 ============================================\n")
	}

	// 发送请求到目标服务器
	resp, respBody, err := s.forwardHTTPSRequest(req, strings.Contains(req.URL.Host, "app.y-i-y.com") && strings.Contains(req.URL.Path, "dewatermark"))
	if err != nil {
		fmt.Printf("❌ 转发HTTPS请求失败: %v\n", err)
		s.sendHTTPSErrorResponseTCP(tlsConn, 502, "Bad Gateway")
		return
	}
	defer resp.Body.Close()

	// 🔍 只有当URL包含特定路径时才输出原始响应信息
	if strings.Contains(req.URL.Host, "app.y-i-y.com") && strings.Contains(req.URL.Path, "dewatermark") {
		fmt.Printf("🔍 ========== 原始HTTPS响应RAW数据 ==========\n")
		fmt.Printf("🔍 Status: %s\n", resp.Status)
		fmt.Printf("🔍 StatusCode: %d\n", resp.StatusCode)
		fmt.Printf("🔍 Proto: %s\n", resp.Proto)
		fmt.Printf("🔍 ProtoMajor: %d\n", resp.ProtoMajor)
		fmt.Printf("🔍 ProtoMinor: %d\n", resp.ProtoMinor)
		fmt.Printf("🔍 TLS: %v\n", resp.TLS != nil)
		if resp.TLS != nil {
			fmt.Printf("🔍 TLS Version: %d\n", resp.TLS.Version)
		}
		fmt.Printf("🔍 Headers (%d total):\n", len(resp.Header))
		for key, values := range resp.Header {
			for _, value := range values {
				fmt.Printf("🔍   %s: %s\n", key, value)
			}
		}
		fmt.Printf("🔍 ============================================\n")
	}

	// 保存原始响应体（用于返回给客户端）
	originalRespBody := make([]byte, len(respBody))
	copy(originalRespBody, respBody)

	// 处理响应体解压（仅用于记录到数据库）
	decompressedBody := respBody
	contentEncoding := resp.Header.Get("Content-Encoding")
	if contentEncoding != "" {
		if decompressed, err := utils.DecompressResponse(respBody, contentEncoding); err == nil {
			decompressedBody = decompressed
		}
	}

	// 创建HTTP响应记录
	httpResp := types.NewHTTPResponse(resp, httpReq.ID)
	httpResp.ID = utils.GenerateResponseID()
	httpResp.Body = utils.FormatBodyForDisplay(decompressedBody, resp.Header.Get("Content-Type"), 1024*1024)
	httpResp.BodySize = int64(len(respBody))
	httpResp.TLSVersion = s.getTLSVersion(tlsConn)

	// 🔍 只有当URL包含特定路径时才输出转换后的响应对象
	if strings.Contains(req.URL.Host, "app.y-i-y.com") && strings.Contains(req.URL.Path, "dewatermark") {
		fmt.Printf("🔍 ========== 转换后的HTTPS响应对象 ==========\n")
		fmt.Printf("🔍 HTTPResponse.HTTPVersion: %s\n", httpResp.HTTPVersion)
		fmt.Printf("🔍 HTTPResponse.StatusCode: %d\n", httpResp.StatusCode)
		fmt.Printf("🔍 HTTPResponse.StatusText: %s\n", httpResp.StatusText)
		fmt.Printf("🔍 HTTPResponse.TLSVersion: %s\n", httpResp.TLSVersion)
		fmt.Printf("🔍 HTTPResponse.Headers (转换后):\n")
		for key, value := range httpResp.Headers {
			fmt.Printf("🔍   %s: %s\n", key, value)
		}
		fmt.Printf("🔍 ============================================\n")
	}

	// 创建事务记录
	transaction := types.NewHTTPTransaction(httpReq, httpResp)
	transaction.ID = utils.GenerateTransactionID()
	transaction.Duration = time.Since(startTime).Milliseconds()

	// 🔍 只有当URL包含特定路径时才输出最终事务对象
	if strings.Contains(req.URL.Host, "app.y-i-y.com") && strings.Contains(req.URL.Path, "dewatermark") {
		fmt.Printf("🔍 ========== 最终HTTPS事务对象 ==========\n")
		fmt.Printf("🔍 Transaction.ID: %s\n", transaction.ID)
		fmt.Printf("🔍 Transaction.Request.Method: %s\n", transaction.Request.Method)
		fmt.Printf("🔍 Transaction.Request.URL: %s\n", transaction.Request.URL)
		fmt.Printf("🔍 Transaction.Request.HTTPVersion: %s\n", transaction.Request.HTTPVersion)
		fmt.Printf("🔍 Transaction.Response.StatusCode: %d\n", transaction.Response.StatusCode)
		fmt.Printf("🔍 Transaction.Response.StatusText: %s\n", transaction.Response.StatusText)
		fmt.Printf("🔍 Transaction.Response.HTTPVersion: %s\n", transaction.Response.HTTPVersion)
		fmt.Printf("🔍 Transaction.Request.TLSVersion: %s\n", transaction.Request.TLSVersion)
		fmt.Printf("🔍 Transaction.Response.TLSVersion: %s\n", transaction.Response.TLSVersion)
		fmt.Printf("🔍 Transaction.Duration: %dms\n", transaction.Duration)
		fmt.Printf("🔍 ============================================\n")
	}

	// 执行规则
	if s.rulesEngine != nil {
		s.wg.Add(1)
		go func() {
			defer s.wg.Done()
			s.executeRules(transaction)
		}()
	}

	// 保存到数据库
	if s.db != nil {
		s.wg.Add(1)
		go func() {
			defer s.wg.Done()
			if err := s.db.SaveTransaction(transaction); err != nil {
				fmt.Printf("❌ 保存HTTPS事务失败: %v\n", err)
			}
		}()
	}

	// 通过WebSocket广播
	if s.wsServer != nil {
		s.wg.Add(1)
		go func() {
			defer s.wg.Done()
			s.wsServer.BroadcastTransaction(transaction)
		}()
	}

	// 发送响应给客户端
	s.sendHTTPSResponseTCP(tlsConn, resp, originalRespBody)

	// 更新统计信息
	s.stats.mu.Lock()
	s.stats.totalRequests++
	s.stats.mu.Unlock()

	fmt.Printf("✅ HTTPS请求处理完成: %s %s -> %d (%dms)\n",
		req.Method, req.URL.String(), resp.StatusCode, time.Since(startTime).Milliseconds())
}

// forwardHTTPSRequest 转发HTTPS请求到目标服务器 - 完全透传
func (s *Server) forwardHTTPSRequest(req *http.Request, isDebugURL bool) (*http.Response, []byte, error) {
	// 创建新的请求以避免RequestURI问题
	newReq, err := http.NewRequest(req.Method, req.URL.String(), req.Body)
	if err != nil {
		return nil, nil, fmt.Errorf("创建新请求失败: %w", err)
	}

	// 完全复制所有请求头，不跳过任何头部，并确保添加必需的头部
	if isDebugURL {
		fmt.Printf("🔍 HTTPS原始请求头数量: %d\n", len(req.Header))
		fmt.Printf("🔍 HTTPS请求协议: %s\n", req.Proto)
	}

	// 特别保存priority头部（如果存在）
	var priorityHeader []string
	if priority := req.Header.Get("priority"); priority != "" {
		priorityHeader = req.Header["priority"] // 获取所有priority值
		if isDebugURL {
			fmt.Printf("🔍 HTTPS发现Priority头部: %v\n", priorityHeader)
		}
	}

	// 先复制所有原始请求头
	for key, values := range req.Header {
		if isDebugURL {
			fmt.Printf("🔍 HTTPS原始请求头: %s = %v\n", key, values)
		}
		for _, value := range values {
			newReq.Header.Add(key, value)
		}
	}

	// 确保priority头部被正确设置（强制重新设置以防丢失）
	if len(priorityHeader) > 0 {
		newReq.Header.Del("priority") // 先删除
		for _, value := range priorityHeader {
			newReq.Header.Add("priority", value) // 重新添加
		}
		if isDebugURL {
			fmt.Printf("🔍 HTTPS强制重新设置Priority头部: %v\n", newReq.Header["priority"])
		}
	}

	// 确保host头部存在（某些客户端可能不发送Host头但设置了req.Host）
	if req.Host != "" && newReq.Header.Get("Host") == "" {
		newReq.Header.Set("Host", req.Host)
		if isDebugURL {
			fmt.Printf("🔍 HTTPS补充Host请求头: %s\n", req.Host)
		}
	}

	if isDebugURL {
		fmt.Printf("🔍 HTTPS转发请求头数量: %d\n", len(newReq.Header))
		fmt.Printf("🔍 HTTPS最终Priority头部: %v\n", newReq.Header["priority"])
	}

	// 保持原始Content-Length
	if req.ContentLength > 0 {
		newReq.ContentLength = req.ContentLength
	}

	// 创建支持HTTP/2的HTTP客户端
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: false, // 验证目标服务器证书
		},
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 10,
		IdleConnTimeout:     90 * time.Second,
	}

	// 启用HTTP/2支持
	if err := http2.ConfigureTransport(transport); err != nil {
		fmt.Printf("⚠️ 配置转发HTTP/2传输失败: %v\n", err)
	}

	client := &http.Client{
		Timeout:   60 * time.Second,
		Transport: transport,
	}

	// 发送请求
	resp, err := client.Do(newReq)
	if err != nil {
		return nil, nil, fmt.Errorf("发送请求失败: %w", err)
	}

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		resp.Body.Close()
		return nil, nil, fmt.Errorf("读取响应体失败: %w", err)
	}

	// 重新设置响应体
	resp.Body = io.NopCloser(bytes.NewReader(respBody))

	return resp, respBody, nil
}

// sendHTTPSResponseTCP 发送HTTPS响应给客户端（TCP版本）- 完全透传
func (s *Server) sendHTTPSResponseTCP(tlsConn *tls.Conn, resp *http.Response, respBody []byte) {
	// 不修改Content-Length，保持原始响应头完全透传

	// 写入状态行
	statusLine := fmt.Sprintf("HTTP/1.1 %d %s\r\n", resp.StatusCode, resp.Status[4:])
	tlsConn.Write([]byte(statusLine))

	// 完全复制原始响应头，不做任何修改
	for key, values := range resp.Header {
		for _, value := range values {
			headerLine := fmt.Sprintf("%s: %s\r\n", key, value)
			tlsConn.Write([]byte(headerLine))
		}
	}

	// 结束头部
	tlsConn.Write([]byte("\r\n"))

	// 发送响应体
	if respBody != nil && len(respBody) > 0 {
		tlsConn.Write(respBody)
	}
}

// sendHTTPSErrorResponseTCP 发送HTTPS错误响应（TCP版本）
func (s *Server) sendHTTPSErrorResponseTCP(tlsConn *tls.Conn, statusCode int, statusText string) {
	response := fmt.Sprintf("HTTP/1.1 %d %s\r\n"+
		"Content-Type: text/plain\r\n"+
		"Content-Length: %d\r\n"+
		"Connection: close\r\n"+
		"\r\n"+
		"%s", statusCode, statusText, len(statusText), statusText)

	tlsConn.Write([]byte(response))
}

// getTLSVersion 获取TLS版本字符串
func (s *Server) getTLSVersion(tlsConn *tls.Conn) string {
	if tlsConn == nil {
		return ""
	}

	state := tlsConn.ConnectionState()
	return utils.GetTLSVersion(state.Version)
}
